from flask.views import MethodView, View
from flask import render_template, redirect, url_for, request, send_from_directory, flash, get_flashed_messages, \
    jsonify, session
from .forms import BlogForms, MessageForms, CommentForms
from .models import *
import os
from sqlalchemy import func
from reguser.checklimit import check_limit
import json
from urllib.request import urlopen

UPLOAD_FOLDER = r'./static/uploads'
ALLOWEd_EXTENSIONS = ['.jpg', '.gif', '.png']


# 检查文件是否为图片
def allowed_file(filename):
    _, ext = os.path.splitext(filename)
    return ext.lower() in ALLOWEd_EXTENSIONS


# 上传图片
class SendFile(MethodView):
    def get(self, filename):
        return send_from_directory(UPLOAD_FOLDER, filename)


# 首页
class BlogIndex(MethodView):
    def get(self, page=1):
        check_limit()

        form = MessageForms()
        arts = Article.query.order_by(Article.id.desc()).paginate(page, per_page=5)
        newart = db.session.query(Article).order_by(Article.id.desc()).limit(3)
        cates = db.session.query(Category).all()
        return render_template('blogobj/blog.html', form=form, arts=arts, newart=newart, cates=cates)

    def post(self, page=1):
        form = MessageForms(request.form)
        msg = Message()
        if form.name.data and form.email.data and form.body.data:
            form.populate_obj(msg)
            db.session.add(msg)
            db.session.commit()
            flash('消息已经收到~')
        else:
            flash('您似乎没有填写完整...每一项都要填哟')
        return redirect(url_for('.blog_index'))


# 分类页面
class CategoryPage(MethodView):
    def get(self, id=None):
        arts = Article.query.filter(Article.categoryid == id).order_by(Article.id.desc()).all()
        newart = db.session.query(Article).order_by(Article.id.desc()).limit(3)
        cates = db.session.query(Category).all()
        return render_template('blogobj/category-page.html', arts=arts, newart=newart, cates=cates)


# AJAX实现搜索功能
class CategoryBlog(MethodView):
    def get(self):
        cates = db.session.query(Category).all()
        return jsonify([cate.to_json() for cate in cates])


class BlogSearch(MethodView):
    def get(self):
        id = int(request.args.get('id'))
        name = request.args.get('name')
        if id in [1, 2, 3, 4, 5]:
            arts = db.session.query(Article).filter(Article.categoryid == id, Article.title.contains(name)).order_by(
                Article.id.desc()).all()
        else:
            if name:
                arts = Article.query.filter(Article.title.contains(name)).all()

        return jsonify([art.to_json() for art in arts])


# AJAX实现搜索功能END


# 统计文章分类数量
class NumCategory(MethodView):
    def get(self):
        nums = db.session.query(func.count(Article.categoryid), Article.categoryid).group_by(Article.categoryid).all()
        num = [{'num': n[0], 'categoryid': n[1]} for n in nums]
        return jsonify(num)


# 博客详情页
class BlogDetail(View):
    methods = ['GET', 'POST']

    def dispatch_request(self, id=0):
        art = db.session.query(Article).filter(Article.id == id).one_or_none()

        newart = db.session.query(Article).order_by(Article.id.desc()).limit(3)
        cates = db.session.query(Category).all()
        this_comments = db.session.query(Comment).filter(Comment.article_id == id).order_by(Comment.id.desc()).all()
        numcomment = db.session.query(Comment).filter(Comment.article_id == id).count()

        form = CommentForms(request.form)
        page = request.form.get('page_id')
        form.name.data = session.get('admin')
        form.ip.data = request.remote_addr
        comments = Comment()
        form.article_id.data = page
        form.releasetime.data = datetime.now()

        if request.method == 'POST' and form.validate():
            form.populate_obj(comments)
            db.session.add(comments)
            db.session.commit()
            return redirect(url_for('.blog_detail', id=page))
        return render_template('blogobj/blog-detail.html', art=art, newart=newart, cates=cates, form=form,
                               this_comments=this_comments, numcomment=numcomment)


# 统计文章访问次数
class NumBrowse(MethodView):
    def post(self, id=0):
        num = db.session.query(Article.numbrowse).filter(Article.id == id).scalar()
        if int(request.form.get('isnew', '0')) == 1:
            num += 1
        db.session.query(Article).filter(Article.id == id).update({Article.numbrowse: num})
        db.session.commit()
        return jsonify({'status': 'ok'})


class BlogPost(MethodView):
    def get(self):
        if check_limit() == 1:
            return redirect(url_for('admin.login'))
        form = BlogForms()
        form.categoryid.choices = [(cate.id, cate.categoryname) for cate in db.session.query(Category).all()]

        newart = db.session.query(Article).order_by(Article.id.desc()).limit(3)
        cates = db.session.query(Category).all()
        return render_template('blogobj/blog-post.html', form=form, newart=newart, cates=cates)

    def post(self):
        form = BlogForms(request.form)
        art = Article()
        img_path = None
        if request.files.get('faceimage'):
            img = request.files.get('faceimage')
            if img and allowed_file(img.filename):
                img_path = datetime.now().strftime('%Y%m%d%H%M%S') + os.path.splitext(img.filename)[1]
                img.save(os.path.join(UPLOAD_FOLDER, img_path))
        form.faceimage.data = img_path
        form.body.data = form.body.data.replace('\r', '').replace('\n', '<br/>').replace('&lt;script&gt;', '<span><</span>script<span>></span>').replace('&lt;/script&gt;', '<span><</span>/script<span>></span>')
        form.populate_obj(art)
        db.session.add(art)
        db.session.commit()
        return redirect(url_for('.blog_index'))


class GetDate(View):
    methods = ['GET', 'POST']

    def dispatch_request(self):
        # ----------------------------------
        # 万年历调用
        # ----------------------------------
        appkey = 'b307187ab210f183652ee65e09d79986'
        date = str(datetime.now().year) + '-' + str(datetime.now().month).lstrip('0') + '-' + str(datetime.now().day).lstrip('0')
        url = 'http://japi.juhe.cn/calendar/day?date={}&key={}'.format(date, appkey)
        data = urlopen(url)
        data = bytes.decode(data.read())
        da = json.loads(data)
        if da.get('error_code') == 0:
            das = da.get('result').get('data')
            return jsonify(das)
